<template>
  <base-modal
    :title="modalTitle"
    :show.sync="addContactDialog"
    width="600px"
    class="edit-contact-dialog"
    @closed="reset"
  >
    <form class="edit-contact-form-container" v-if="init">
      <form-builder
        :fields="fields"
        class="edit-contact-form"
        ref="form"
        :value="form"
        @update="update"
      >
        <template slot="phone" slot-scope="{field}">
          <form-item :label="field.displayName" :validation="validation" :form="form">
            <form-text
              :field="field"
              :value="form.phone"
              @update="update"
              :placeholder="field.placeholder"
            />
          </form-item>
        </template>
        <template slot="productId" slot-scope="{field}">
          <form-item :label="field.displayName">
            <BizSearchProductSelect
              :placeholder="$t('customer.detail.editContactDialog.productSelectPlaceholder')"
              :remote-method="fetchCustomerProducts"
              v-model="form.productId"
              :ifNeedCustomer="false"
              :multiple="field.setting.isMulti"
              autoComplete="off"
            />
            <!-- <el-select
              :placeholder="field.placeholder"
              class="contact-product-select"
              popper-class="contact-product-select-popper"
              :multiple="field.setting.isMulti"
              v-model="form.productId"
              :popper-append-to-body="false"
            >
              <el-option
                :key="product.id"
                :label="product.name"
                :value="product.id"
                v-for="product in products">
                <div class="contact-product-select-item">
                  <div class="contact-product-select-item-name">
                    {{ product.name }}
                  </div>
                  <div class="contact-product-select-item-attr">
                    编号： {{ product.serialNumber }}
                  </div>
                  <div class="contact-product-select-item-attr">
                    类型：{{ product.type }}
                  </div>
                </div>
              </el-option>
            </el-select> -->
          </form-item>
        </template>
      </form-builder>
    </form>
    <div class="dialog-footer" slot="footer">
      <el-button type="plain-third" @click="addContactDialog = false">{{$t('common.base.close')}}</el-button>
      <el-button @click="submit" type="primary" :disabled="pending">{{$t('common.base.save')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import * as FormUtil from '@src/component/form/util';
import * as LinkmanApi from '@src/api/LinkmanApi';
import { getValidProductIds, searchCustomerLinkmanForProduct, getProductList } from '@src/api/ProductApi';
import { getLinkmanFields } from '@src/api/CustomerApi';
import { createRemoteValidate } from '@src/util/validator';
import { isBasicEditionHideProduct } from '@shb-lib/version'
import BizSearchProductSelect from '@src/component/business/BizSearchProductSelect/BizSearchProductSelect'
import i18n from '@src/locales';
import { formatAddress } from 'pub-bbx-utils';
/** mixin */
import { VersionControlOtherMixin } from '@src/mixins/versionControlMixin'

export default {
  name: 'edit-contact-dialog',
  mixins: [VersionControlOtherMixin],
  components: {
    BizSearchProductSelect
  },
  props: {
    customer: {
      type: Object,
      default: () => ({})
    },
    originalValue: {
      type: Object,
      default: () => ({})
    },
    isPhoneUnique: Boolean
  },
  data() {
    return {
      init: false,
      addContactDialog: false,
      pending: false,
      products: [],
      addresses: [],
      form: {
        name: null,
        remark: '',
        sex: '',
        position: '',
        department: '',
        address: '', // address的ID
        customId: '',
        customer: {},
        id: '',
        phone: null,
        email: null,
        productId: [], // 数组，包含产品对象
        remindMe: '',
      },
      loadData: false,
      createOriginalValue: {},
      werfenFields: [],
    };
  },
  computed: {
    action() {
      return this.originalValue.name ? 'edit' : 'create';
    },
    customerId() {
      return (this.customer && this.customer.id) || '';
    },
    isEdit() {
      return this.action === 'edit';
    },
    linkmanId() {
      return (this.originalValue && this.originalValue.id) || '';
    },
    fields() {
      let fields = [
        {
          formType: 'text',
          fieldName: 'name',
          displayName: i18n.t('common.fields.contact.displayName'),
          placeholder: `[${i18n.t('common.placeholder.limitInput', { limit: 50 })}]`,
          isNull: 0
        },
        {
          formType: 'phone',
          fieldName: 'phone',
          displayName: i18n.t('common.fields.phone.displayName'),
          placeholder: i18n.t('common.placeholder.phoneOrEmail'),
          isNull: 1
        },
        {
          formType: 'email',
          fieldName: 'email',
          displayName: i18n.t('common.fields.email.displayName'),
          placeholder: i18n.t('common.placeholder.emailOrPhone'),
          isNull: 1
        },
        {
          formType: 'select',
          fieldName: 'sex',
          displayName: i18n.t('common.fields.sex.displayName'),
          placeholder: i18n.t('common.placeholder.select'),
          isNull: 1,
          setting: {
            dataSource: [
              {
                text: i18n.t('common.fields.sex.options.man'),
                value: '男',
              },
              {
                text: i18n.t('common.fields.sex.options.woman'),
                value: '女'
              },
            ]
          }
        },
        {
          formType: 'text',
          fieldName: 'position',
          displayName: i18n.t('common.fields.position.displayName'),
          placeholder: '',
          isNull: 1
        },
        {
          formType: 'text',
          fieldName: 'department',
          displayName: i18n.t('common.fields.department.displayName'),
          placeholder: '',
          isNull: 1
        },
        {
          formType: 'textarea',
          fieldName: 'remark',
          displayName: i18n.t('common.fields.remark.displayName'),
          placeholder: `[${i18n.t('common.placeholder.limitInput', { limit: 500 })}]`,
          isNull: 1
        },
        {
          formType: 'select',
          fieldName: 'productId',
          displayName: i18n.t('common.fields.relationProduct.displayName'),
          placeholder: i18n.t('common.placeholder.select'),
          isNull: 1,
          setting: {
            isMulti: true,
            dataSource: this.products || []
          }
        },
        {
          formType: 'select',
          fieldName: 'address',
          displayName: i18n.t('common.fields.relationAddress.displayName'),
          placeholder: i18n.t('common.placeholder.select'),
          isNull: 1,
          setting: {
            dataSource: this.addresses || []
          }
        }
      ];

      if (this.werfenFields.length) {
        fields = [...fields, ...this.werfenFields]
      }

      fields.forEach(f => {
        if (['phone', 'email'].includes(f.fieldName)) {
          f.isNullRelationFields = fields.filter(field =>
            ['phone', 'email'].includes(field.fieldName)
          )
        }
      })

      if (this.isBasicEditionHideProduct) {
        return fields.filter(item => item.fieldName !== 'productId');
      }

      fields = fields.filter(item => {

        if (item.fieldName === 'email') {
          return this._isShowEmail
        }

        return true

      });

      return fields;

    },
    modalTitle() {
      return this.originalValue.name ? this.$t('customer.detail.editContactDialog.editContact') : this.$t('customer.detail.editContactDialog.addContact');
    },
    validation() {
      return this.isPhoneUnique ? (...rest) => {
        let value = rest[0]
        // 原先电话必填，现在存在非必填的情况，如果没填电话，此处不做是否存在相同号码的校验，否则接口会返回已存在
        if (!value) return null
        let fn = createRemoteValidate(LinkmanApi.checkUnique4Phone, (value, field) => {
          return {
            id: this.originalValue.id || '',
            phone: value
          }
        })
        return fn(...rest)
      } : true
    },
    // 基础版功能是否显示
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct()
    }
  },
  methods: {
    genPlaceholder(field) {
      return FormUtil.genPlaceholder(field);
    },
    async fetchWerfenFields() {
      try {
        this.werfenFields = [];
        const { result, code } = await getLinkmanFields()
        if (code !== 0) return;
        this.werfenFields = result || [];
      } catch (e) {
        console.error('fetchWerfenFields error', e);
      }
    },
    async submit() {
      try {
        const validateRes = await this.$refs.form.validate();
        if (!validateRes) return;

        this.pending = true;

        const params = {
          ...this.form,
          customer:{ id: this.customer.id },
          // productId: this.products
          //   .filter(p => this.form.productId.some(pId => pId === p.value))
          //   .map(p => ({
          //     id: p.value,
          //     name: p.text
          //   }))
        };
        if (this.werfenFields.length) {
          params.attribute = {
            remindMe: !!this.form.remindMe
          }
        }
        delete params.remindMe;

        let result = {};

        if (this.action === 'create') {
          result = await this.$http.post('/linkman/createByJson', params);
        } else {
          result = await this.$http.post('/linkman/updateByJson', params);
        }

        if (result.status != 0) {
          this.pending = false;
          return this.$platform.notification({
            title: this.$t('customer.detail.editContactDialog.submitNotify.title') ,
            message:
              result.message
              || (this.action === 'create' ? this.$t('customer.detail.editContactDialog.submitNotify.createMsg') : this.$t('customer.detail.editContactDialog.submitNotify.editMsg')),
            type: 'error'
          });
        }

        this.pending = false;
        this.addContactDialog = false;
        this.$emit('Preservation',{ ...this.form, id: result.data })
        // 新建、编辑工单页面新建联系人
        this.$eventBus.$emit('task_create_or_edit.update_linkman', { ...this.form, id: result.data });
        // 新建、编辑事件页面新建联系人
        this.$eventBus.$emit('event_create_or_edit.update_linkman', { ...this.form, id: result.data });
        // 产品详情关联客户新建联系人
        this.$eventBus.$emit('product_create_or_edit.update_linkman', { ...this.form, id: result.data });


        this.reset();
        this.$eventBus.$emit('customer_contact_table.update_linkman_list');
        this.$eventBus.$emit('customer_info_record.update_record_list');
        this.$eventBus.$emit('customer_detail_view.update_statistical_data');
        this.$eventBus.$emit('customer_detail_view.update_customer_detail');
        this.$eventBus.$emit('customer_contact.update_contact_list');

        // if (this.action === 'create') {
        //   this.$eventBus.$emit(
        //     'customer_detail_view.select_tab',
        //     'customer-contact-table'
        //   );
        // }
      } catch (e) {
        this.pending = false;
        console.error('addContactDialog submit catch e', e);
      }
    },
    reset() {
      this.form = {
        name: null,
        remark: '',
        sex: '',
        position: '',
        department: '',
        address: '',
        customId: '',
        customer: {},
        id: '',
        phone: null,
        email: null,
        productId: []
      };
      this.init = false;
    },
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      // 手机号去空格
      if(fieldName == 'phone') {
        newValue = newValue.trim()
      }
      if (this.$appConfig.debug) {
        console.info(
          `[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(
            newValue
          )}`
        );
      }
      this.$set(this.form, fieldName, newValue);
    },
    openDialog(createOriginalValue = {}) {
      this.addContactDialog = true;

      // 沃分用户新增推送服务通知字段
      this.fetchWerfenFields();

      if (this.action === 'edit') {
        this.matchValueToForm(this.originalValue);
      }

      this.createOriginalValue = createOriginalValue;

      this.fetchAddress();
      // this.action === 'edit' ? this.fetchEditProducts() : this.fetchProducts();
      // this.fetchProducts();
      this.init = true;
    },
    matchValueToForm(val) {
      console.log(val)
      const {
        name,
        remark,
        sex,
        position,
        department,
        customerId,
        customer,
        id,
        phone,
        email,
        attribute,
      } = val;
      this.form = {
        name,
        remark,
        sex: ['男', '女'].indexOf(sex) === -1 ? '' : sex,
        position,
        department,
        address: '',
        customId: customerId || customer.id,
        customer: customer || {},
        id,
        phone,
        email,
        // productId: []
        productId: [],
        remindMe: attribute?.remindMe ? 1 : 0
      };

      this.getExistProduct(val.productId, customerId || customer.id)

      // 联系人的产品和地址在获取到产品和地址的列表之后过滤掉被删除的再给form使用
    },
    getExistProduct(products, customerId) {
      let params = {
        productIds: products.map(v => v.id),
        customerId
      }
      getValidProductIds(params).then(res => {
        this.form.productId = products.filter(v => res.result.includes(v.id))
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        if(!this.form.productId?.length) {
          this.form.productId = products
        }
      })
    },
    fetchAddress() {
      return this.$http
        .get('/customer/address/list', {
          customerId: this.customer.id,
          pageSize: 100000,
          pageNum: 1
        })
        .then(res => {
          this.addresses = res.list.map(p => ({
            text: formatAddress(p),
            value: p.id
          }));

          // 把被删除的地址过滤掉
          const address = this.originalValue.address;
          if (address && this.addresses.some(a => a.value === address)) {
            this.form.address = address;
          }

          return this.addresses;
        })
        .catch(err => console.error('fetchAddress catch err', err));
    },
    fetchProducts() {
      return getProductList({
          customerId: this.customer.id,
          pageSize: 100000,
          pageNum: 1
        })
        .then(res => {
          this.products = (res.list || []).map(p => ({
            name: p.name,
            id: p.id,
            serialNumber: p.serialNumber,
            type: p.type,
            text: p.name,
            value: p.id
          }));
          // 把被删除的产品过滤掉
          const productId = this.originalValue.productId;
          if (productId && productId.length) {
            this.form.productId = productId
              .map(p => p.id)
              .filter(pId => this.products.some(p => p.value === pId));
          }

          // this.form.productId = this.products.map(p => p.value);
          return this.products;
        })
        .catch(err => console.error('fetchProducts catch err', err));
    },
    // 查询产品列表
    fetchCustomerProducts(params) {
      let { keyword, pageNum, pageSize } = params;
      let queryParams = {
        pageNum,
        keyword,
        pageSize,
        customerId: this.customer.id,
      }

      return getProductList(queryParams).then(res => {
        if (!res || !res.list) return;

        res.list = res.list.map(item =>
          Object.freeze({
            label: item?.name || '',
            value: item?.id || '',
            text: item.name || '',
            name: item.name || '',
            id: item.id || '',
            serialNumber: item.serialNumber || '',
            type: item.type || '',
          })
        );
        res.pageNum = pageNum
        res.pageSize = pageSize
        res.hasNextPage = res.total > res.pageNum * res.pageSize

        return res;
      });
    },
    fetchEditProducts() {
      return searchCustomerLinkmanForProduct({
        linkmanId: this.linkmanId,
        customerId: this.customer.id,
        pageSize: 0,
        pageNum: 1,
      })
        .then(res => {
          let list = res.list || []
          this.products = list.map(p => ({
            text: p.name,
            value: p.id
          }));
          // 把被删除的产品过滤掉
          const productId = this.originalValue.productId;
          if (productId && productId.length) {
            this.form.productId = productId
              .map(p => p.id)
              .filter(pId => this.products.some(p => p.value === pId));
          }

          this.form.productId = this.products.map(p => p.value);
          return this.products;
        })
        .catch(err => console.error('fetchProducts catch err', err));
    },
  }
};
</script>

<style lang="scss">
.edit-contact-dialog {
  .base-modal-body {
    padding: 15px 30px 0;
  }

  .edit-contact-form-container {
    width: 100%;
    margin: 0 auto;

    .edit-contact-form {
      width: 100%;
      padding: 10px 0 5px;
    }

    .form-item label {
      /*text-align: right;*/
      width: 80px;
    }

    .form-builder {
      width: 100%;
    }

    .form-item-control {
      // max-width: calc(100% - 80px);
    }
  }

  .dialog-footer {
    text-align: right;
    padding: 0px 0px 15px;
  }
}
</style>

<style lang="scss" scoped>
  .contact-product-select {
    width: 100%;
  }
  ::v-deep .contact-product-select-popper {
    .el-select-dropdown__item {
      height: auto;
      padding: 0 10px;
    }
    .contact-product-select-item {
      padding: 5px 0;
      color: #262626;
      .contact-product-select-item-name {
        font-size: 14px;
        font-weight: 500;
        line-height: 24px;
      }

      .contact-product-select-item-attr {
        line-height: 24px;
        font-size: 12px;
        color: #666;
      }
    }
    .el-select-dropdown__item.selected {
      height: auto;
      padding: 0 10px;
      .contact-product-select-item-name {
        color: $color-primary-light-6;
      }
    }
  }
</style>
